package com.app.couponsharelife.ui.adapter

import android.graphics.Paint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.data.bean.TaobaoGoodBean
import com.app.couponsharelife.databinding.HomeListItemBinding
import com.app.couponsharelife.ui.listener.OnClickListener
import java.text.DecimalFormat

class HomeGalleryListAdapter(private val list: MutableList<TaobaoGoodBean>,
                             private val listener: OnClickListener) :
        androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {

    fun setData(data: List<TaobaoGoodBean>) {
        list.clear()
        list.addAll(data)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
        return ViewHolder(DataBindingUtil.inflate(
                LayoutInflater.from(parent.context), R.layout.home_list_item, parent, false))
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, position: Int) {
        val df = DecimalFormat("#0.0")
        val good = list[position]
        (holder as ViewHolder).databinding.tvGoodPlatform.text = if (good.user_type == "0") "淘宝" else "天猫"
        holder.databinding.tvGoodName.text = good.title
        holder.databinding.tvCouponPrice.text = df.format(good.final_price.toDouble())
        holder.databinding.tvOriginalPrice.text = df.format(good.original_price.toDouble())
        holder.databinding.tvOriginalPrice.paintFlags = holder.databinding.tvOriginalPrice.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
        Glide.with(holder.databinding.ivGoodImage).asBitmap()
                .apply(RequestOptions().placeholder(R.drawable.ic_good_place_holder))
                .load(good.pict_url)
                .into(holder.databinding.ivGoodImage)
    }

    inner class ViewHolder(val databinding: HomeListItemBinding) : androidx.recyclerview.widget.RecyclerView.ViewHolder(databinding.root) {
        init {
            databinding.root.setOnClickListener {
                if (adapterPosition != -1) {
                    listener.click(adapterPosition, list[adapterPosition])
                }
            }
        }
    }
}